package org.xxpay.manage.channelagentmch.ctrl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.xxpay.core.common.annotation.MethodLog;
import org.xxpay.core.common.constant.Constant;
import org.xxpay.core.common.constant.MchConstant;
import org.xxpay.core.common.constant.RetEnum;
import org.xxpay.core.common.domain.BizResponse;
import org.xxpay.core.common.domain.XxPayPageRes;
import org.xxpay.core.common.domain.XxPayResponse;
import org.xxpay.core.common.util.MD5Util;
import org.xxpay.core.entity.ChannelAgentMchInfo;
import org.xxpay.core.entity.ChannelMchInfo;
import org.xxpay.core.entity.PayPassage;
import org.xxpay.core.entity.PayProduct;
import org.xxpay.manage.common.ctrl.BaseController;
import org.xxpay.manage.common.service.RpcCommonService;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Controller
@RequestMapping(Constant.MGR_CONTROLLER_ROOT_PATH + "/channelagentmch_info")
public class ChannelAgentMchInfoController extends BaseController {



    @Autowired
    private RpcCommonService rpcCommonService;
    /**
     * 查询代理渠道商信息
     * @return
     */
    @RequestMapping("/get")
    @ResponseBody
    public ResponseEntity<?> get(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);
        Long channelAgentMchId = getLongRequired(param, "channelAgentMchId");
        ChannelAgentMchInfo channelAgentMchInfo = rpcCommonService.rpcChannelAgentMchInfoService.findBychannelAgentMchId(channelAgentMchId);
        return ResponseEntity.ok(XxPayResponse.buildSuccess(channelAgentMchInfo));
    }





    /**
     *
     *用于渠道商添加渠道商上级所需要的信息
     * 查出所有渠道代理商
     */

    @RequestMapping("/getSupChannelAgentMch")
    @ResponseBody
    public ResponseEntity<?> getSupChannelAgentMch(HttpServletRequest request) {
        System.out.println("====================");
        JSONObject param = getJsonParam(request);
        Byte channelAgentMchLevel =4;

        List<ChannelAgentMchInfo> channelAgentMchInfoList  = rpcCommonService.rpcChannelAgentMchInfoService.findByChannelAgentMchLevel(channelAgentMchLevel);
        System.out.println("==="+channelAgentMchInfoList.toString());
        return ResponseEntity.ok(XxPayResponse.buildSuccess(channelAgentMchInfoList));
    }

    /**
     * 查询代理渠道商信息
     * @return
     */
    @RequestMapping("/list")
    @ResponseBody
    public ResponseEntity<?> list(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);
        ChannelAgentMchInfo channelAgentMchInfo = getObject(param, ChannelAgentMchInfo.class);
        int count = rpcCommonService.rpcChannelAgentMchInfoService.count(channelAgentMchInfo);
        if(count == 0) return ResponseEntity.ok(XxPayPageRes.buildSuccess());
        List<ChannelAgentMchInfo> channelAgentMchInfoList = rpcCommonService.rpcChannelAgentMchInfoService.select((getPageIndex(param) - 1) * getPageSize(param), getPageSize(param), channelAgentMchInfo);
        List<JSONObject> objects = new LinkedList<>();
        for(ChannelAgentMchInfo info : channelAgentMchInfoList) {
            JSONObject object = (JSONObject) JSON.toJSON(info);
 //           object.put("loginAgentUrl", buildLoginAgentUrl(info));  // 生成登录地址
//            AgentAccount account = rpcCommonService.rpcAgentAccountService.findByAgentId(info.getChannelMchId());
//            object.put("agentBalance", account.getBalance());  // 账户余额

            //  PayPassage findById(Integer id);
            objects.add(object);
        }
        Map<String ,Object> ps = new HashMap<String, Object>();
//        AgentAccount accountRecord = new AgentAccount();
//        accountRecord.setAgentId(channelMchInfo.getChannelMchId());
//        ps.put("allAgentBalance",  rpcCommonService.rpcAgentAccountService.sumAgentBalance(accountRecord));
        return ResponseEntity.ok(XxPayPageRes.buildSuccess(objects, ps, count));
    }

    /**
     * 新增代理商信息
     * @return
     */
    @RequestMapping("/add")
    @ResponseBody
    @MethodLog( remark = "新增渠道代理商" )
    public ResponseEntity<?> add(HttpServletRequest request, ChannelAgentMchInfo channelAgentMchInfo) {
        //  JSONObject param = getJsonParam(request);
        //   ChannelMchInfo channelMchInfo = getObject(param, ChannelMchInfo.class);
        System.out.println("----------------"+channelAgentMchInfo.toString());
        // 设置默认登录密码
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String rawPassword = MchConstant.CHANNELAGENTMCH_DEFAULT_PAY_PASSWORD;
        channelAgentMchInfo.setPassword(encoder.encode(rawPassword));
        channelAgentMchInfo.setLastPasswordResetTime(new Date());
        // 设置默认支付密码
        String payPassword = MchConstant.CHANNELAGENTMCH_DEFAULT_PAY_PASSWORD;
        channelAgentMchInfo.setPayPassword(MD5Util.string2MD5(payPassword));
        // 确认用户名不能重复
        if(rpcCommonService.rpcChannelAgentMchInfoService.findByUserName(channelAgentMchInfo.getUserName()) != null) {
            return ResponseEntity.ok(BizResponse.build(RetEnum.RET_AGENT_USERNAME_USED));
        }
        // 确认手机不能重复
        if(rpcCommonService.rpcChannelAgentMchInfoService.findByMobile(channelAgentMchInfo.getMobile()) != null) {
            return ResponseEntity.ok(BizResponse.build(RetEnum.RET_MCH_MOBILE_USED));
        }
        // 确认邮箱不能重复
        if(rpcCommonService.rpcChannelAgentMchInfoService.findByEmail(channelAgentMchInfo.getEmail()) != null) {
            return ResponseEntity.ok(BizResponse.build(RetEnum.RET_MCH_EMAIL_USED));
        }

//        // 验证一级代理ID
//        if (agentInfo.getParentAgentId() == null) agentInfo.setParentAgentId(0L);
//        if(agentInfo.getParentAgentId() != 0) {
//            if (rpcCommonService.rpcAgentInfoService.findByAgentId(agentInfo.getParentAgentId()) == null) {
//                return ResponseEntity.ok(BizResponse.build(RetEnum.RET_MCH_PARENTAGENTID_NOT_EXIST));
//            }
//            if(rpcCommonService.rpcAgentInfoService.findByAgentId(agentInfo.getParentAgentId()).getAgentLevel() != 1){
//                return ResponseEntity.ok(BizResponse.build(RetEnum.RET_MCH_PARENTAGENTID_NOT_EXIST));
//            }
//            agentInfo.setAgentLevel((byte) 2);
//        }else{
//            agentInfo.setAgentLevel((byte) 1);
//        }

        int count = rpcCommonService.rpcChannelAgentMchInfoService.add(channelAgentMchInfo);
        if(count != 1) ResponseEntity.ok(XxPayResponse.build(RetEnum.RET_COMM_OPERATION_FAIL));
        return ResponseEntity.ok(BizResponse.buildSuccess());
    }

    /**
     * 删除
     * @return
     */
    @RequestMapping("/delete")
    @ResponseBody
    @MethodLog( remark = "删除渠道代理商" )
    public ResponseEntity<?> delete(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);
        String channelAgentMchIds = getStringRequired(param, "channelAgentMchIds");
        String[] ids = channelAgentMchIds.split(",");
        List<Long> rids = new LinkedList<>();
        for(String channelAgentMchId : ids) {
            if(NumberUtils.isDigits(channelAgentMchId)) rids.add(Long.parseLong(channelAgentMchId));
        }
        //  int batchDeleteRole(List<Long> roleIds);
        rpcCommonService.rpcChannelAgentMchInfoService.batchDeleteChannelAgentMch(rids);
        // rpcCommonService.rpcSysService.batchDeleteRole(rids);
        return ResponseEntity.ok(BizResponse.buildSuccess());
    }
    @RequestMapping("/updateStatus")
    @ResponseBody
    @MethodLog( remark = "修改渠道商状态" )
    public ResponseEntity<?> updateStatus(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);
        String channelAgentMchId = getStringRequired(param, "channelAgentMchId");
        String status = getStringRequired(param, "status");
        ChannelAgentMchInfo channelAgentMchInfo = new ChannelAgentMchInfo();
        System.out.println("=====channelAgentMchId===="+channelAgentMchId);
        System.out.println("=====status===="+status);
        channelAgentMchInfo.setChannelAgentMchId((Long.valueOf(channelAgentMchId)));
        Byte channelAgentMchStatus;
        if(status.equals("true")){
            channelAgentMchStatus=1;
        }else {
            channelAgentMchStatus=0;
        }
        channelAgentMchInfo.setStatus(channelAgentMchStatus);
        rpcCommonService.rpcChannelAgentMchInfoService.update(channelAgentMchInfo);

        return ResponseEntity.ok(BizResponse.buildSuccess());
    }



//    private String buildLoginAgentUrl(ChannelMchInfo channelMchInfo) {
//        // 将商户ID+商户密码+密钥 做32位MD5加密转大写,作为token传递给商户系统
//        String password = channelMchInfo.getPassword();
//        String secret = "Abc%$G&!!!128G";
//        String rawToken = channelMchInfo.getChannelMchId() + password + secret;
//        String token = MD5Util.string2MD5(rawToken).toUpperCase();
//        String loginAgentUrl = mainConfig.getLoginAgentUrl();
//        return String.format(loginAgentUrl, channelMchInfo.getChannelMchId(), token);
//    }
}